<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    let person = {
        name: 'jack',
        hobbies: ['music', 'games', 'reading']
    }

    function SimpleCopy(obj) {
        let result = {}
        for (let i in obj) {
            if (obj.hasOwnProperty(i)) {
                result[i] = obj[i]
            }
        }

        return result
    }

    let copy1 = SimpleCopy(person)
    console.log('拷贝后是:', copy1) // jack football
    person.name = "marry"
    person.hobbies[0] = "football"

    console.log('修改后是：', copy1)  // jack football
    // 当修改了字符串后，发现不变，但修改了数组元素值，它会改变，这就是浅拷贝

    // 浅拷贝的实现方式还有   Object.assign()      展开运算符 ...      array.slice()


    // 使用递归进行深拷贝
    function deepCopy(obj) {

        let myObj = new obj.constructor(); // 拷贝数组类型
        console.log(myObj)

        if (myObj === null) return obj
        if (myObj instanceof Date) return new Date(obj)
        if (myObj instanceof RegExp) return new RegExp(obj)
        if (typeof obj !== 'object') return obj

        for (let i in obj) {
            if (obj.hasOwnProperty(i)) {
                myObj[i] = deepCopy(obj[i]) // 递归
            }
        }
        return myObj
    }

    let stu = {name: 'jack', memo: {age: 20, info: [{hobbies: 'music'}]}}
    let copy2 = deepCopy(stu)
    console.log('深拷贝：', copy2)
    stu.memo.info[0].hobbies = "games"
    console.log(copy2)

    //  除了上面的递归进行深拷贝，还可以使用 JSON.parse(JSON.stringify() )  来完成，但是它不能实现 function 的深拷贝
</script>
</body>
</html>